<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="产品类别" prop="classType">
        <el-select v-model="queryParams.classType" placeholder="请选择产品类别" clearable>
          <el-option
            v-for="dict in dict.type.product_class"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
        >新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-setting"
          size="mini"
          @click="handleSetColumns"
        >设置表头
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <!-- 动态表格 -->
    <el-table v-loading="loading" :data="productList" @selection-change="handleSelectionChange" border>
      <el-table-column type="selection" width="55" align="center"/>

      <el-table-column label="序号" type="index" align="center" width="60">
        <template slot-scope="scope">
          <span>{{ (queryParams.pageNum - 1) * queryParams.pageSize + scope.$index + 1 }}</span>
        </template>
      </el-table-column>

      <el-table-column label="更新时间" align="center" prop="updateTime" width="180"/>

      <!-- 动态表头 -->
      <el-table-column
        v-for="column in tableColumns"
        :key="column.field"
        :label="column.label"
        :prop="column.field"
        align="center"
        :width="column.width || 'auto'"
        :show-overflow-tooltip="true"
      >
        <template slot-scope="scope">
          <span>{{ scope.row[column.field] || '-' }}</span>
        </template>
      </el-table-column>

      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="150">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
          >编辑
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
          >删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改产品对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="80%" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <!-- 产品核心信息区域 -->
        <div class="fixed-fields-section">
          <div class="section-title">产品核心信息</div>
          <el-row :gutter="24">
            <el-col :span="8">
              <el-form-item label="产品类别" prop="classType">
                <el-select v-model="form.classType" placeholder="请选择产品类别">
                  <el-option
                    v-for="dict in dict.type.product_class"
                    :key="dict.value"
                    :label="dict.label"
                    :value="dict.value"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="价格" prop="price">
                <el-input v-model="form.price" placeholder="请输入价格" style="width: 100%;" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="分区" prop="partition">
                <el-input v-model="form.partition" placeholder="请输入分区" style="width: 100%;" />
              </el-form-item>
            </el-col>
          </el-row>
        </div>

        <!-- 动态字段区域：除了价格、分区、类别之外的字段 -->
        <div v-if="getDynamicColumns().length > 0" class="dynamic-fields">
          <div class="fields-section-title">产品详细信息</div>
          <el-row :gutter="24" v-for="column in getDynamicColumns()" :key="column.field">
            <el-col :span="12">
              <el-form-item :label="column.label" :prop="column.field">
                <el-input
                  v-model="form[column.field]"
                  :placeholder="'请输入' + column.label"
                  v-if="column.type === 'input' || !column.type"
                  style="width: 100%;"
                />
                <el-input-number
                  v-model="form[column.field]"
                  :placeholder="'请输入' + column.label"
                  :precision="column.precision || 0"
                  v-else-if="column.type === 'number'"
                  style="width: 100%;"
                />
              </el-form-item>
            </el-col>
          </el-row>
        </div>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

         <!-- 设置表头对话框 -->
     <el-dialog title="设置表格表头" :visible.sync="columnsOpen" width="1200px" append-to-body>
       <el-form ref="columnsForm" :model="columnsForm" :rules="columnsRules" label-width="80px">
        <div class="columns-container">
          <div class="columns-header">
            <span class="columns-title">表格列配置</span>
            <el-button type="primary" size="mini" icon="el-icon-plus" @click="addColumn">添加列</el-button>
          </div>

          <div v-if="columnsForm.columns && columnsForm.columns.length > 0" class="columns-list">
            <transition-group name="sortable-list" tag="div">
              <div
                v-for="(column, index) in columnsForm.columns"
                :key="column.key || index"
                class="column-item"
                draggable="true"
                @dragstart="handleDragStart($event, index)"
                @dragover="handleDragOver($event)"
                @dragenter="handleDragEnter($event, index)"
                @dragend="handleDragEnd"
              >
                <el-row :gutter="20">
                  <el-col :xs="24" :sm="6">
                    <el-form-item :label="'列名'" :prop="'columns.' + index + '.label'" :rules="{ required: true, message: '列名不能为空', trigger: 'blur' }">
                      <el-input v-model="column.label" placeholder="如：价格" />
                    </el-form-item>
                  </el-col>
                  <el-col :xs="24" :sm="6">
                    <el-form-item :label="'字段名'" :prop="'columns.' + index + '.field'" :rules="{ required: true, message: '字段名不能为空', trigger: 'blur' }">
                      <el-input v-model="column.field" placeholder="如：price" />
                    </el-form-item>
                  </el-col>
                  <el-col :xs="24" :sm="4">
                    <el-form-item :label="'类型'">
                      <el-select v-model="column.type" placeholder="选择类型" style="width: 100%">
                        <el-option label="文本" value="input"></el-option>
                        <el-option label="数值" value="number"></el-option>
                      </el-select>
                    </el-form-item>
                  </el-col>
                  <el-col :xs="24" :sm="4">
                    <el-form-item :label="'宽度'">
                      <el-input v-model="column.width" placeholder="如：120" />
                    </el-form-item>
                  </el-col>
                  <el-col :xs="24" :sm="4">
                    <el-form-item label="操作">
                      <el-button
                        type="danger"
                        size="mini"
                        icon="el-icon-delete"
                        @click="removeColumn(index)"
                      >删除</el-button>
                    </el-form-item>
                  </el-col>
                </el-row>
              </div>
            </transition-group>
          </div>

          <div v-else class="columns-empty">
            <el-empty description="暂无列配置，请点击添加列"></el-empty>
          </div>
        </div>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitColumnsForm">确 定</el-button>
        <el-button @click="cancelColumns">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listProduct, saveProduct, delProduct } from "@/api/official/product"
import request from "@/utils/request"

export default {
  name: "Product",
  dicts: ['product_class'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 产品表格数据
      productList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        classType: undefined
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        name: [
          { required: true, message: "产品名称不能为空", trigger: "blur" }
        ],
        classType: [
          { required: true, message: "产品类别不能为空", trigger: "change" }
        ]
      },
      // 表格列配置 - 包含固定字段和动态字段
      tableColumns: [],
      // 固定字段列表
      fixedColumns: [
        { label: '价格', field: 'price', type: 'input', width: '120' },
        { label: '分区', field: 'partition', type: 'input', width: '120' }
      ],
      // 表头设置相关
      columnsOpen: false,
      columnsForm: {
        columns: []
      },
      columnsRules: {
        columns: [
          {
            required: true,
            validator: (rule, value, callback) => {
              if (!this.columnsForm.columns || this.columnsForm.columns.length === 0) {
                callback(new Error('至少需要添加1列'));
              } else {
                callback();
              }
            },
            trigger: 'change'
          }
        ]
      },
      // 拖拽相关
      draggingIndex: -1
    }
  },
  created() {
    this.getList()
    this.getTableColumns()
  },
  methods: {
    /** 查询产品列表 */
    getList() {
      this.loading = true
      listProduct(this.queryParams).then(response => {
        // 处理每条数据，将dynamicFields解析并合并到产品对象中
        this.productList = response.rows.map(product => {
          const processedProduct = { ...product }

          // 如果存在dynamicFields字段且是字符串，尝试解析为对象
          if (product.dynamicFields && typeof product.dynamicFields === 'string') {
            try {
              // 解析dynamicFields为对象
              let dynamicFields = JSON.parse(product.dynamicFields)

              // 处理可能存在的嵌套dynamicFields
              if (dynamicFields.dynamicFields && typeof dynamicFields.dynamicFields === 'string') {
                try {
                  dynamicFields = JSON.parse(dynamicFields.dynamicFields)
                } catch (e) {
                  console.error('解析嵌套的dynamicFields失败:', e)
                }
              }

              // 将动态字段合并到产品对象中
              Object.assign(processedProduct, dynamicFields)
            } catch (e) {
              console.error('解析dynamicFields失败:', e)
            }
          }

          return processedProduct
        })

        this.total = response.total
        this.loading = false
      })
    },

    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        id: undefined,
        classType: undefined,
        price: undefined,
        partition: undefined
      }
      // 重置动态字段
      this.getDynamicColumns().forEach(column => {
        this.$set(this.form, column.field, undefined)
      })
      this.resetForm("form")
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm")
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length != 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.open = true
      this.title = "添加产品"
    },
    /** 设置表头按钮操作 */
    handleSetColumns() {
      this.resetColumnsForm()
      this.getTableColumns()
      this.columnsOpen = true
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      // 直接从列表行数据中获取字段信息
      const formData = { ...row }

      // 如果row中包含dynamicFields字段且是字符串，尝试解析为对象
      if (row.dynamicFields && typeof row.dynamicFields === 'string') {
        try {
          const dynamicFields = JSON.parse(row.dynamicFields)
          // 将动态字段合并到表单数据中
          Object.assign(formData, dynamicFields)
        } catch (e) {
          console.error('解析dynamicFields失败:', e)
        }
      }

      this.form = formData
      this.open = true
      this.title = "修改产品"
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          // 构建新的参数格式
          const requestData = {
            id: this.form.id, // 保留id用于修改场景
            classType: this.form.classType,
            price: this.form.price,
            partition: this.form.partition,
            // 将动态字段转换为JSON字符串
            dynamicFields: JSON.stringify(this.getDynamicFormFields())
          }

          saveProduct(requestData).then(response => {
            this.$modal.msgSuccess(this.form.id ? "修改成功" : "新增成功")
            this.open = false
            this.getList()
          })
        }
      })
    },

    /** 获取动态表单字段 */
    getDynamicFormFields() {
      const dynamicFields = {}
      const fixedFieldNames = ['id', 'classType', 'price', 'partition', 'name', 'dynamicFields'] // 明确排除所有固定字段和dynamicFields自身

      // 将表单中所有非固定字段放入dynamicFields，确保不包含任何固定字段
      Object.keys(this.form).forEach(key => {
        if (!fixedFieldNames.includes(key)) {
          dynamicFields[key] = this.form[key]
        }
      })

      return dynamicFields
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids
      this.$modal.confirm('是否确认删除产品编号为"' + ids + '"的数据项？').then(function() {
        return delProduct(ids)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess("删除成功")
      }).catch(() => {})
    },
    // 表头相关方法
      // 获取表格列配置
    getTableColumns() {
      request.get('/official/product/getColumns').then(response => {
        // 获取动态字段（不包含固定字段）
        // 如果接口返回成功但数据为空，则显示空，不使用默认配置
        let dynamicColumns = response && response.code === 200 && response.data ? response.data : []

        // 如果返回的数据包含sortNum字段，则根据sortNum排序
        if (dynamicColumns && dynamicColumns.length > 0 && 'sortNum' in dynamicColumns[0]) {
          dynamicColumns = dynamicColumns.sort((a, b) => a.sortNum - b.sortNum)
        }

        // 合并固定字段和动态字段
        this.tableColumns = [...this.fixedColumns, ...dynamicColumns]
      }).catch(() => {
        // 接口调用失败时，只显示固定字段，不显示动态字段
        this.tableColumns = [...this.fixedColumns]
      })
    },

    /** 获取动态字段（排除固定字段） */
    getDynamicColumns() {
      const fixedFieldNames = ['price', 'partition']
      return this.tableColumns.filter(column => !fixedFieldNames.includes(column.field))
    },

    // 获取默认动态列配置（不包含固定字段）
    getDefaultDynamicColumns() {
      return [
        { label: '单节点CPU配置', field: 'cpuConfig', type: 'input', width: '180' },
        { label: '单节点总核数', field: 'totalCores', type: 'number', width: '140' },
        { label: '主频 (GHz)', field: 'frequency', type: 'number', precision: 2, width: '120' },
        { label: '单节点内存 (GB)', field: 'memory', type: 'number', width: '150' },
        { label: '单节点峰值性能 (Tflops)', field: 'peakPerformance', type: 'number', precision: 2, width: '200' },
        { label: '单核峰值性能 (Gflops)', field: 'singleCorePerformance', type: 'number', precision: 1, width: '180' }
      ]
    },
    // 重置表头表单 - 只包含动态字段
    resetColumnsForm() {
      // 过滤出动态字段（排除固定字段）
      const fixedFieldNames = this.fixedColumns.map(col => col.field)
      const dynamicColumns = this.tableColumns.filter(col => !fixedFieldNames.includes(col.field))

      // 为每列添加唯一key
      const columnsWithKey = dynamicColumns.map(col => ({
        ...col,
        key: col.key || Date.now() + Math.random()
      }))

      this.columnsForm = {
        columns: [...columnsWithKey]
      }
      this.resetForm("columnsForm")
    },
    // 提交表头表单
    submitColumnsForm() {
      this.$refs["columnsForm"].validate(valid => {
        if (valid) {
          // 为每个列添加sortNum字段，从0开始排序
          const columnsWithSortNum = this.columnsForm.columns.map((column, index) => ({
            ...column,
            sortNum: index // 从0开始排序
          }))

          // 保存动态字段配置（包含sortNum）
          request.post('/official/product/saveColumns', columnsWithSortNum).then(response => {
            if (response && response.code === 200) {
              this.$modal.msgSuccess("表头保存成功")
              this.columnsOpen = false
              this.getTableColumns() // 重新加载列配置，会自动合并固定字段和动态字段
              this.getList() // 重新加载主列表接口
            } else {
              this.$modal.msgError(response.msg || "保存失败")
            }
          }).catch(() => {
            this.$modal.msgError("保存失败")
          })
        }
      })
    },
    // 取消表头设置
    cancelColumns() {
      this.columnsOpen = false
      this.resetColumnsForm()
    },
    // 添加列
    addColumn() {
      if (!this.columnsForm.columns) {
        this.$set(this.columnsForm, 'columns', [])
      }
      // 为每列添加唯一key用于拖拽排序
      this.columnsForm.columns.push({
        key: Date.now(), // 唯一标识，用于拖拽时正确识别元素
        label: '',
        field: '',
        type: 'input',
        width: ''
      })
      // 触发表单验证
      this.$nextTick(() => {
        this.$refs.columnsForm.validateField('columns')
      })
    },
    // 删除列
    removeColumn(index) {
      this.columnsForm.columns.splice(index, 1)
      // 触发表单验证
      this.$nextTick(() => {
        this.$refs.columnsForm.validateField('columns')
      })
    },

    // 拖拽开始事件
    handleDragStart(e, index) {
      e.dataTransfer.effectAllowed = 'move'
      e.dataTransfer.setData('text/html', e.target.innerHTML)
      this.draggingIndex = index
      e.target.classList.add('dragging')
    },

    // 拖拽经过事件
    handleDragOver(e) {
      e.preventDefault()
      e.dataTransfer.dropEffect = 'move'
      return false
    },

    // 拖拽进入事件
    handleDragEnter(e, index) {
      e.preventDefault()
      if (this.draggingIndex !== index) {
        // 获取当前拖拽元素和目标元素
        const movingItem = this.columnsForm.columns[this.draggingIndex]
        this.columnsForm.columns.splice(this.draggingIndex, 1)
        this.columnsForm.columns.splice(index, 0, movingItem)
        this.draggingIndex = index
      }
    },

    // 拖拽结束事件
    handleDragEnd(e) {
      e.target.classList.remove('dragging')
      this.draggingIndex = -1
    }
  }
}
</script>

<style scoped>
.columns-container {
  border: 1px solid #e4e7ed;
  border-radius: 4px;
  padding: 16px;
}

.columns-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
  padding-bottom: 8px;
  border-bottom: 1px solid #f0f0f0;
}

.columns-title {
  font-weight: bold;
  color: #303133;
}

.columns-list {
  margin-bottom: 16px;
}

.column-item {
  background: #fafafa;
  border: 1px solid #e4e7ed;
  border-radius: 4px;
  padding: 16px;
  margin-bottom: 12px;
  width: 100%;
}

.column-item .el-row {
  margin: 0 !important;
}

.column-item .el-col {
  padding: 0 10px;
}

.column-item .el-form-item {
  margin-bottom: 0;
}

.column-item .el-input,
.column-item .el-select {
  width: 100%;
}

.column-item:last-child {
  margin-bottom: 0;
}

/* 拖拽相关样式 */
.column-item {
  cursor: move;
  transition: all 0.3s;
}

.column-item:hover {
  background-color: #f5f5f5;
}

.column-item.dragging {
  opacity: 0.5;
  background-color: #e6f7ff;
  border-color: #91d5ff;
}

.sortable-list-move {
  transition: transform 0.3s;
}

/* 拖拽提示样式 */
.column-item.drag-over {
  border: 1px dashed #1890ff;
  background-color: #e6f7ff;
}

.columns-empty {
  text-align: center;
  padding: 20px;
  color: #909399;
}
/* 固定字段区域样式 */
.fixed-fields-section {
  background-color: #f0f9ff;
  border: 1px solid #b3d8ff;
  padding: 15px;
  border-radius: 4px;
  margin-bottom: 20px;
}

/* 动态字段样式 */
.dynamic-fields {
  padding: 15px;
  background-color: #fafafa;
  border-radius: 4px;
}

/* 区域标题样式 */
.section-title,
.fields-section-title {
  font-weight: bold;
  color: #303133;
  margin-bottom: 15px;
  padding-bottom: 10px;
  border-bottom: 1px solid #ebeef5;
  font-size: 14px;
}

/* 表单元素间距优化 */
.el-form-item {
  margin-bottom: 18px;
}

/* 对话框整体优化 */
.el-dialog__body {
  padding: 20px;
}

/* 确保输入框、数字输入框和选择器样式一致 */
.el-input,
.el-input-number,
.el-select {
  width: 100%;
}
</style>
